package com.lollipop.programming.thread.deadlock;

import lombok.extern.slf4j.Slf4j;

/**
 * @Author Lollipop
 * @Date 2025/4/7 16:26
 * @Description 死锁demo
 */
@Slf4j
public class DeadlockDemo {
    // 定义两个锁对象
    private static final Object lock1 = new Object();
    private static final Object lock2 = new Object();

    public static void main(String[] args) {
        // 线程1：先获取lock1，再尝试获取lock2
        Thread thread1 = new Thread(() -> {
            synchronized (lock1) {
                log.info("线程1获取到lock1");
                try {
                    // 睡眠1秒，确保线程2能获取到lock2
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                log.info("线程1尝试获取lock2...");
                synchronized (lock2) {
                    log.info("线程1获取到lock2");
                }
            }
        });

        // 线程2：先获取lock2，再尝试获取lock1
        Thread thread2 = new Thread(() -> {
            synchronized (lock2) {
                log.info("线程2获取到lock2");
                try {
                    // 睡眠1秒，确保线程1能获取到lock1
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    log.error("线程 {} 执行过程中被中断", e.getMessage());
                }
                log.info("线程2尝试获取lock1...");
                synchronized (lock1) {
                    log.info("线程2获取到lock1");
                }
            }
        });

        // 启动线程
        thread1.start();
        thread2.start();

        // 等待线程结束
        try {
            thread1.join();
            thread2.join();
        } catch (InterruptedException e) {
            log.error("程序异常：{}", e.getMessage());
        }

        log.info("程序结束");
    }
}

